package com.klikmee.sms.chat.web.usecases;

import java.util.ArrayList;
import org.json.JSONException;
import com.dotexe.webframework.core.ClientApplication;
import com.dotexe.webframework.core.datasources.ObjectDataSource;
import com.dotexe.webframework.core.triggers.Trigger;
import com.klikmee.sms.chat.web.dao.TemplateDAO;
import com.klikmee.sms.chat.web.util.SpringBeansLookup;
import com.klikmee.sms.services.chat.model.Template;

public class TemplateDetailsForm extends ClientApplication {

	private ObjectDataSource dsTemplate;
	private ArrayList<String> bcTemplate;
	
	private Template template;
	private boolean editTemplate;
	
	public void load() throws Exception {
		super.load();
		
		this.dsTemplate = new ObjectDataSource("dsTemplate");
		this.getDataSources().add(this.dsTemplate);

		this.bcTemplate = new ArrayList<String>();
		this.bcTemplate.add("Name");
		this.bcTemplate.add("Template");
		this.bcTemplate.add("Active");

		this.triggers.add(new Trigger(this, "btnSaveClick"));
		this.triggers.add(new Trigger(this, "btnCancelClick"));
	}

	@Override
	public void start() throws Exception {
		super.start();
		
		this.dsTemplate.setSource(template);
		this.dsTemplate.bind(bcTemplate);
	}

	public void btnSaveClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		TemplateDAO twmplateDAO = SpringBeansLookup.getBean(TemplateDAO.class);

		template.setName(((Template) this.dsTemplate.getSource()).getName());
		template.setTemplate(((Template) this.dsTemplate.getSource()).getTemplate());
		template.setActive(((Template) this.dsTemplate.getSource()).getActive());

		if (editTemplate) {
			twmplateDAO.edit(template);
		} else {
			twmplateDAO.create(template);
		}
		
		this.hide();
	}

	public void btnCancelClick() throws InstantiationException, IllegalAccessException, JSONException, Exception {
		this.hide();
	}

	public void setTemplate(Template template) {
		this.template = template;
	}

	public Template getTemplate() {
		return template;
	}

	public void setEditTemplate(boolean editTemplate) {
		this.editTemplate = editTemplate;
	}

	public boolean getEditTemplate() {
		return editTemplate;
	}

}
